package labb3.FileHandling;

import labb3.Media;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

/**
 * Class used to load a MediaCollection ArrayList from an serialized file.
 *
 * @author Mikko Puustinen
 * @version 0.5, 2007-okt-18
 */
public class LoadSerialized implements CollectionLoader {
    private final String path;

    /**
     * Initializes an instance of LoadSerialized and attaches a path.
     *
     * @param path path to the file to load.
     */
    public LoadSerialized(String path) {
        this.path = path;
    }

    /**
     * Reads the file and load all the serialized Media objects from it.
     *
     * @return the ArrayList containing the Media objects. If some error occurs
     *         during loading or reading the ArrayList will be created but it
     *         will be empty.
     *
     * @throws ClassNotFoundException Not implemented in this version.
     * @throws IOException            if something went wrong while loading the
     *                                file or reading it.
     * @see java.io.Serializable
     * @see labb3.Media
     */
    @SuppressWarnings({"unchecked"})
    public ArrayList<Media> loadCollection() throws ClassNotFoundException, IOException {
        FileInputStream fis;
        ObjectInputStream ois = null;
        ArrayList<Media> media;

        try {
            fis = new FileInputStream(path);
            ois = new ObjectInputStream(fis);
            media = (ArrayList<Media>)ois.readObject();
        } catch (IOException e) {
            media = new ArrayList<Media>();
            throw new IOException("Error while reading file");
        } catch (ClassNotFoundException e) {
            throw new ClassNotFoundException("Error while reading file");
        }

        finally {
            if (ois != null) {
                ois.close();
            }
        }

        return media;
    }
}
